<template>
  <div class="banner">
    <div class="banner-bg" :style="{ backgroundImage: `url(${activeFilm?.poster})` }"></div>
    <div class="swiper" ref="swiperRef">
      <div class="swiper-wrapper">
        <div class="swiper-slide" v-for="item in slides" :key="item.filmId">
            <img :src="item.poster" alt="">
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.banner {
  box-sizing: border-box;
  height: 160px;
  padding: 15px 0;
  position: relative;
  background-color: honeydew;
  overflow: hidden;
}
.banner-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  filter: blur(30px)
}
.swiper {
  height: 100%;
  width: 100%;
  // background-color: #ccc;
}
.swiper-slide {
  text-align: center;
  font-size: 18px;
  background: #fff;

  /* Center slide text vertically */
  display: -webkit-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  -webkit-justify-content: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  -webkit-align-items: center;
  align-items: center;
  transition: 300ms;
  transform: scale(0.8);
}
.swiper-slide-active{
  transform: scale(1);
}
img{
    display: block;
    width: 100%;
    height: 100%;
}
</style>

<script lang="ts" setup>
import { ref, onMounted,watch,computed } from 'vue'
import swiper, { type Swiper } from 'swiper'
import 'swiper/swiper-bundle.css'
import type { Film } from '@/api/interface';

const swiperRef = ref<HTMLDivElement | null>(null)
let mySwiper: Swiper
const props = defineProps<{
    slides: Film.Item[] //当前影院的电影列表
    filmId?:number  //当前选择的电影ID
}>()

const emit = defineEmits(['update:filmId'])


//当前激活电影
const activeFilm = computed(()=>{
  if(props.filmId){
    return props.slides.find(item=>item.filmId === props.filmId) || props.slides[0]
  } else {
    return props.slides[0]
  }
})

watch(
    ()=>props.slides,
    (newVal)=>{
    //通知swiper重新更新一下
    mySwiper && mySwiper.update()
    //计算当前需要激活的下标
    const index = newVal.findIndex((item)=>item.filmId === props.filmId) || 0
    //通过slideTO切换
    mySwiper && mySwiper.slideTo(index)
    },
    {
        flush:'post'
    }
)

onMounted(() => {
  //计算initialSlide
  // const initialSlide = props.slides.findIndex(item=>item.filmId===props.filmId || 0)

  mySwiper = new swiper(swiperRef.value!, {
    // initialSlide: initialSlide, //初始化页面展示
    slidesPerView: 4, //一屏显示多个slide
    spaceBetween: 30, //slide之间的距离
    centeredSlides: true, //激活的slide在中间
    slideToClickedSlide: true //点击激活
  })
  //监听mySwiper的 slideChange事件
  // 触发父组件修改filmId
  mySwiper.on('slideChange',(ins)=>{
    
    const filmId = props.slides[ins.activeIndex].filmId
    emit('update:filmId',filmId)
  })      
})
</script>
